#include "../logs/ltylog.h"
#include <unistd.h>

using namespace std;

enum class TimeGap {
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public ltylog::LogSink {
public:
    //构造时传入文件名并打开，将操作句柄ofs管理起来
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename) {
        switch (gap_type) {
            case TimeGap::GAP_SECOND:
                _gap_size = 1;
                break;
            case TimeGap::GAP_MINUTE:
                _gap_size = 60;
                break;
            case TimeGap::GAP_HOUR:
                _gap_size = 3600;
                break;
            case TimeGap::GAP_DAY:
                _gap_size = 3600 * 24;
                break;
        }
        _cur_gap = _gap_size == 1 ? ltylog::util::Date::now() : ltylog::util::Date::now() % _gap_size;//获取当前是第几个时间段
        std::string filename = createNewFile();
        ltylog::util::File::createDirectory(ltylog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    void log(const char *data, size_t len) {
        time_t cur = ltylog::util::Date::now();
        if ((cur % _gap_size) != _cur_gap) {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }
private:
    std::string createNewFile() {
        time_t t = ltylog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        return filename.str();//filename是stringstream，要转换成string

    }
private:
    std::string _basename;
    std::ofstream _ofs;//操作句柄
    size_t _cur_gap;//当前时间段
    size_t _gap_size;//时间段大小
};

int main() {
    std::unique_ptr<ltylog::LoggerBuilder> builder(new ltylog::GloablLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(ltylog::LogLevel::value::WARN);
    builder->buildFormatter("[%c]%m%n");
    builder->buildLoggerType(ltylog::LoggerType::LOGGER_ASYNC);
    builder->buildSink<RollByTimeSink>("./logfile/roll-async-by-size",TimeGap::GAP_SECOND);

    ltylog::Logger::ptr logger=builder->build();
    size_t cur = ltylog::util::Date::now();
    while(ltylog::util::Date::now()<cur+5)
    {
        logger->fatal("测试日志");
        // FATAL("%s","测试日志");
        usleep(1000);
    }

    return 0;
}
